<template>
  <div class="craft-operation-manager">
    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <h3 class="page-title">工艺工序管理</h3>
      </div>
      <div class="toolbar-right">
        <el-button type="primary" @click="addCraft" :icon="Plus">
          新增工艺
        </el-button>
      </div>
    </div>

    <!-- 工艺数据表格 -->
    <el-table
      ref="craftTableRef"
      :data="craftData"
      :loading="craftLoading"
      style="width: 100%; min-height: 300px"
      row-key="id"
      :expand-row-keys="expandedRows"
      @expand-change="handleExpandChange"
      :max-height="600"
    >
      <!-- 展开列 -->
      <el-table-column type="expand">
        <template #default="{ row }">
          <div class="operation-expand-content">
            <!-- 工序流程可视化 -->
            <div class="operation-visualization">
              <div class="visualization-header">
                <div class="header-left">
                  <h4>{{ row.craftName }} - 工序流程预览</h4>
                  <el-tag size="small" type="info" class="operation-count">
                    {{ getOperationsByCraftId(row.id).length }} 个工序
                  </el-tag>
                </div>
                <div class="visualization-actions">
                  <el-button
                    type="primary"
                    size="default"
                    @click="openOperationDesigner(row)"
                  >
                    <el-icon><Setting /></el-icon>
                    设计工序
                  </el-button>
                </div>
              </div>



              
              <div class="visualization-wrapper">
                <OperationFlowVisualization
                  :operations="getOperationsByCraftId(row.id)"
                  :key="`visualization-${row.id}-${visualizationKey}`"
                  @operation-click="handleOperationClick"
                />
              </div>
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 工艺编号 -->
      <el-table-column prop="craftCode" label="工艺编号" width="150" />

      <!-- 工艺名称 -->
      <el-table-column prop="craftName" label="工艺名称" min-width="200" />

      <!-- 工艺总时长 -->
      <el-table-column
        prop="craftTotalStdTime"
        label="工艺总时长(小时)"
        width="150"
      >
        <template #default="{ row }">
          {{ row.craftTotalStdTime || "-" }}
        </template>
      </el-table-column>

      <!-- 产品名称 -->
      <el-table-column prop="productName" label="产品名称" min-width="200">
        <template #default="{ row }">
          {{ getProductName(row.craftProductId) }}
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="250" fixed="right">
        <template #default="{ row }">
          <el-button
            type="text"
            size="small"
            @click="editCraft(row)"
            class="edit-btn"
          >
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <el-button
            type="text"
            size="small"
            @click="deleteCraft(row)"
            class="delete-btn"
          >
            <el-icon><Delete /></el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 工艺表单对话框 -->
    <CraftFormDialog
      v-model="craftDialogVisible"
      :craft-data="currentEditCraft"
      @saved="handleCraftSaved"
    />

    <!-- 工序表单对话框 -->
    <OperationFormDialog
      v-model="operationDialogVisible"
      :operation-data="currentEditOperation"
      :craft-info="currentCraft"
      :all-operations="getOperationsByCraftId(currentCraft?.id)"
      @saved="handleOperationSaved"
    />

    <!-- 全屏流程图对话框 -->
    <el-dialog
      v-model="fullScreenVisible"
      :title="`${fullScreenCraft?.craftName} - 工序流程图`"
      width="90%"
      :before-close="() => (fullScreenVisible = false)"
      class="fullscreen-flow-dialog"
    >
      <div class="fullscreen-flow-container">
        <OperationFlowVisualization
          :operations="getOperationsByCraftId(fullScreenCraft?.id)"
          :key="`fullscreen-${fullScreenCraft?.id}-${visualizationKey}`"
          @operation-click="handleOperationClick"
        />
      </div>

      <template #footer>
        <el-button @click="fullScreenVisible = false">关闭</el-button>
        <el-button type="primary" @click="refreshVisualization">
          <el-icon><Refresh /></el-icon>
          刷新流程
        </el-button>
      </template>
    </el-dialog>

    <!-- 工序设计器 -->
    <OperationDesigner
      v-if="designerCraft"
      v-model="designerVisible"
      :craft-info="designerCraft"
      @refresh="handleDesignerRefresh"
    />
  </div>
</template>

<script>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Edit, Delete, Setting } from "@element-plus/icons-vue";
import OperationFlowVisualization from "./OperationFlowVisualization.vue";
import CraftFormDialog from "./CraftFormDialog.vue";
import OperationFormDialog from "./OperationFormDialog.vue";
import OperationDesigner from "./OperationDesigner.vue";
import { craftApi } from "@/api/craft";
import { operationApi } from "@/api/operation";
import { basicProductApi } from "@/api/basicProduct";

export default {
  name: "CraftOperationManager",
  components: {
    Edit,
    Delete,
    Setting,
    OperationFlowVisualization,
    CraftFormDialog,
    OperationFormDialog,
    OperationDesigner,
  },
  setup() {
    // 表格引用
    const craftTableRef = ref();

    // 加载状态
    const craftLoading = ref(false);
    const operationLoading = ref(false);

    // 数据
    const craftData = reactive([]);
    const operationData = reactive([]);
    const productList = ref([]);

    // 展开行
    const expandedRows = ref([]);

    // 可视化刷新键
    const visualizationKey = ref(0);

    // 全屏显示相关状态
    const fullScreenVisible = ref(false);
    const fullScreenCraft = ref(null);

    // 工序设计器状态
    const designerVisible = ref(false);
    const designerCraft = ref(null);

    // 对话框控制
    const craftDialogVisible = ref(false);
    const operationDialogVisible = ref(false);

    // 当前编辑的工艺和工序
    const currentCraft = ref(null);
    const currentEditCraft = ref(null);
    const currentEditOperation = ref(null);

    // 根据工艺ID获取工序数据
    const getOperationsByCraftId = (craftId) => {
      if (!craftId) return [];
      // 先找到工艺
      const craft = craftData.find((c) => c.id === craftId);
      if (!craft) return [];

      // 根据工艺编码过滤工序（兼容craftId和craftCode两种情况）
      const operations = operationData.filter(
        (op) => op.craftId === craftId || op.craftCode === craft.craftCode,
      );
      return operations;
    };

    // 加载产品列表
    const loadProductList = async () => {
      try {
        const response = await basicProductApi.getProductsByCurrentTenant();
        console.log("产品列表加载成功:", response);
        if (response && response.data) {
          productList.value = response.data;
        }
      } catch (error) {
        console.error("加载产品列表失败:", error);
      }
    };

    // 根据产品ID获取产品名称
    const getProductName = (productId) => {
      if (!productId) return "-";
      const product = productList.value.find((p) => p.id === productId);
      return product ? product.productName : "-";
    };

    // 加载工艺数据
    const loadCraftData = async () => {
      try {
        craftLoading.value = true;
        const response = await craftApi.queryCraftByTenantId();
        console.log("工艺数据加载成功:", response);
        if (response && response.data) {
          craftData.splice(0, craftData.length, ...response.data);
        }
      } catch (error) {
        console.error("加载工艺数据失败:", error);
        ElMessage.error("加载工艺数据失败: " + (error.message || "未知错误"));
      } finally {
        craftLoading.value = false;
      }
    };

    // 根据工艺ID加载工序数据
    const loadOperationDataByCraftId = async (craftId, craftCode) => {
      try {
        operationLoading.value = true;
        console.log(`正在加载工艺ID ${craftId} 的工序数据...`);

        const response = await operationApi.queryOperationByCraftId({
          craftId,
        });
        console.log(`工艺ID ${craftId} 的工序数据加载成功:`, response);

        if (response && response.data) {
          // 移除该工艺的旧工序数据（使用craftCode或craftId）
          const otherOperations = operationData.filter(
            (op) => op.craftCode !== craftCode && op.craftId !== craftId,
          );
          // 添加新的工序数据
          operationData.splice(
            0,
            operationData.length,
            ...otherOperations,
            ...response.data,
          );
        }
      } catch (error) {
        console.error(`加载工艺ID ${craftId} 的工序数据失败:`, error);
        ElMessage.error("加载工序数据失败: " + (error.message || "未知错误"));
      } finally {
        operationLoading.value = false;
      }
    };

    // 展开行变化处理
    const handleExpandChange = async (row, expandedRowsList) => {
      console.log("12312312312312312312312");
      console.log(expandedRowsList);
      console.log(row);
      currentCraft.value = row;
      console.log("展开工艺，工艺信息:", row);
      await loadOperationDataByCraftId(row.id, row.craftCode);
    };

    // 刷新可视化
    const refreshVisualization = () => {
      visualizationKey.value++;
    };

    // 全屏显示流程图
    const showFullScreenFlow = (craft) => {
      fullScreenCraft.value = craft;
      fullScreenVisible.value = true;
    };

    // 打开工序设计器
    const openOperationDesigner = (craft) => {
      console.log("打开工序设计器:", craft);
      designerCraft.value = craft;
      designerVisible.value = true;
    };

    // 设计器关闭后刷新
    const handleDesignerRefresh = async () => {
      console.log("设计器关闭，刷新数据");
      // 重新加载工艺列表
      await loadCraftData();
      // 如果有展开的工艺，刷新其工序数据
      if (designerCraft.value) {
        await loadOperationDataByCraftId(
          designerCraft.value.id,
          designerCraft.value.craftCode,
        );
        refreshVisualization();
      }
    };

    // 工序点击处理
    const handleOperationClick = (operation) => {
      console.log("点击工序:", operation);
    };

    // 新增工艺
    const addCraft = () => {
      currentEditCraft.value = null;
      craftDialogVisible.value = true;
    };

    // 编辑工艺
    const editCraft = (row) => {
      currentEditCraft.value = { ...row };
      craftDialogVisible.value = true;
    };

    // 工艺保存成功回调
    const handleCraftSaved = async (savedCraft) => {
      console.log("工艺保存成功，准备刷新数据:", savedCraft);

      // 判断是新增还是编辑
      if (savedCraft && savedCraft.id && currentEditCraft.value) {
        // 编辑模式：查找并更新单条数据
        const index = craftData.findIndex((item) => item.id === savedCraft.id);
        if (index > -1) {
          // 更新已有数据，保留完整对象结构
          Object.assign(craftData[index], savedCraft);
          console.log("工艺数据已局部更新");

          // 短暂高亮提示用户数据已更新
          setTimeout(() => {
            ElMessage.success({
              message: "工艺表格已刷新",
              duration: 1500,
              showClose: true,
            });
          }, 300);
        } else {
          // 如果找不到，重新加载整个列表
          await loadCraftData();
        }
      } else {
        // 新增模式：重新加载整个列表以获取服务端生成的完整数据
        console.log("新增工艺，重新加载整个列表");
        await loadCraftData();

        // 提示用户数据已刷新
        setTimeout(() => {
          ElMessage.success({
            message: "工艺表格已刷新",
            duration: 1500,
            showClose: true,
          });
        }, 300);
      }
    };

    // 删除工艺
    const deleteCraft = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除工艺 "${row.craftName}" 吗？删除后该工艺下的所有工序也将被删除。`,
          "确认删除",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          },
        );

        await craftApi.deleteCraft(row.id);
        ElMessage.success("工艺删除成功");

        // 从本地数据中移除
        const index = craftData.findIndex((item) => item.id === row.id);
        if (index > -1) {
          craftData.splice(index, 1);
        }

        // 移除该工艺的工序数据
        const remainingOperations = operationData.filter(
          (op) => op.craftCode !== row.craftCode,
        );
        operationData.splice(0, operationData.length, ...remainingOperations);
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除工艺失败:", error);
          ElMessage.error("删除工艺失败: " + (error.message || "未知错误"));
        }
      }
    };

    // 新增工序
    const addOperation = (craft) => {
      currentCraft.value = craft;
      currentEditOperation.value = null;
      operationDialogVisible.value = true;
    };

    // 编辑工序
    const editOperation = (operation, craft) => {
      currentCraft.value = craft;
      currentEditOperation.value = { ...operation };
      operationDialogVisible.value = true;
    };

    // 工序保存成功回调
    const handleOperationSaved = async (savedOperation) => {
      console.log("工序保存成功，准备刷新数据:", savedOperation);

      if (savedOperation && savedOperation.id && currentEditOperation.value) {
        // 编辑模式：查找并更新单条数据
        const index = operationData.findIndex(
          (item) => item.id === savedOperation.id,
        );
        if (index > -1) {
          Object.assign(operationData[index], savedOperation);
          console.log("工序数据已局部更新");
        } else {
          // 如果找不到，重新加载该工艺的工序数据
          if (currentCraft.value) {
            await loadOperationDataByCraftId(
              currentCraft.value.id,
              currentCraft.value.craftCode,
            );
          }
        }
      } else {
        // 新增模式：重新加载该工艺的工序数据
        if (currentCraft.value) {
          console.log("新增工序，重新加载工序列表");
          await loadOperationDataByCraftId(
            currentCraft.value.id,
            currentCraft.value.craftCode,
          );
        }
      }

      // 刷新可视化
      refreshVisualization();
    };

    // 删除工序
    const deleteOperation = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除工序 "${row.operationName}" 吗？`,
          "确认删除",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          },
        );

        await operationApi.deleteOperation(row.id);
        ElMessage.success("工序删除成功");

        // 从本地数据中移除
        const index = operationData.findIndex((item) => item.id === row.id);
        if (index > -1) {
          operationData.splice(index, 1);
        }

        refreshVisualization();
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除工序失败:", error);
          ElMessage.error("删除工序失败: " + (error.message || "未知错误"));
        }
      }
    };

    // 组件挂载时加载数据
    onMounted(() => {
      loadCraftData();
      loadProductList();
      // 工序数据在展开工艺时按需加载，不需要全部加载
    });

    return {
      // 表格引用
      craftTableRef,

      // 数据
      craftData,
      operationData,
      productList,

      // 状态
      craftLoading,
      operationLoading,
      expandedRows,
      visualizationKey,

      // 对话框控制
      craftDialogVisible,
      operationDialogVisible,
      fullScreenVisible,
      fullScreenCraft,
      designerVisible,
      designerCraft,
      currentEditCraft,
      currentEditOperation,
      currentCraft,

      // 方法
      getOperationsByCraftId,
      getProductName,
      handleExpandChange,
      refreshVisualization,
      showFullScreenFlow,
      openOperationDesigner,
      handleDesignerRefresh,
      handleOperationClick,
      addCraft,
      editCraft,
      deleteCraft,
      handleCraftSaved,
      addOperation,
      editOperation,
      deleteOperation,
      handleOperationSaved,
    };
  },
};
</script>

<style scoped>
.craft-operation-manager {
  width: 100%;
  padding: 20px;
}

/* 工具栏样式 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.toolbar-left {
  flex: 1;
}

.page-title {
  margin: 0;
  color: white;
  font-size: 20px;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.toolbar-right {
  display: flex;
  gap: 10px;
}

/* 主按钮样式优化 */
.toolbar-right .el-button--primary {
  background: white;
  border-color: white;
  color: #667eea;
  font-weight: 500;
  padding: 10px 24px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.toolbar-right .el-button--primary:hover {
  background: #f0f0f0;
  border-color: #f0f0f0;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* ==================== 展开区域样式 ==================== */
.operation-expand-content {
  padding: 0;
  background: transparent;
  margin: 0;
}

.operation-visualization {
  background: linear-gradient(to bottom, #f8f9fa 0%, #ffffff 100%);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  margin: 16px;
}

.visualization-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0px 20px;
  /* background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); */
  border-bottom: 2px solid rgba(255, 255, 255, 0.1);
}

.visualization-header .header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.visualization-header h4 {
  margin: 0;
  color: black;
  font-size: 16px;
  font-weight: 600;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.operation-count {
  background: rgba(255, 255, 255, 0.95) !important;
  border: 1px solid rgba(255, 255, 255, 0.3) !important;
  color: #667eea !important;
  font-weight: 500;
}

.visualization-wrapper {
  padding: 24px;
  background: white;
  min-height: 400px;
}

.visualization-actions .el-button {
  background: rgba(255, 255, 255, 0.95);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: #667eea;
  font-weight: 500;
  transition: all 0.3s ease;
}

.visualization-actions .el-button:hover {
  background: white;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

/* 表格样式调整 */
:deep(.el-table__expanded-cell) {
  padding: 0 !important;
}

:deep(.el-table__expanded-cell .cell) {
  padding: 0 !important;
}

/* 确保表格宽度为100% */
:deep(.el-table) {
  width: 100% !important;
}

:deep(.el-table__header-wrapper) {
  width: 100% !important;
}

:deep(.el-table__body-wrapper) {
  width: 100% !important;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}

/* 编辑删除按钮样式 */
.edit-btn {
  color: #714b67 !important;
}

.edit-btn:hover {
  color: #922575 !important;
}

.delete-btn {
  color: #f5222d !important;
}

.delete-btn:hover {
  color: #ff4d4f !important;
}

/* 可视化操作按钮样式 */
.visualization-actions {
  display: flex;
  gap: 8px;
}

/* 全屏对话框样式 */
.fullscreen-flow-dialog :deep(.el-dialog) {
  height: 90vh;
  display: flex;
  flex-direction: column;
}

.fullscreen-flow-dialog :deep(.el-dialog__body) {
  flex: 1;
  overflow: hidden;
  padding: 20px;
}

.fullscreen-flow-container {
  width: 100%;
  height: calc(90vh - 200px);
  background-color: #f8f9fa;
  border-radius: 8px;
  overflow: auto;
}
</style>
